package com.ten.member.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ten.common.core.entity.EduTeacher;
import com.ten.common.core.entity.TbCheckTeacher;
import com.ten.common.core.entity.TbMember;
import com.ten.common.core.util.JWTUtil;
import com.ten.common.core.vo.Result;
import com.ten.member.dao.TbMemberDao;
import com.ten.member.service.TbMemberService;
import com.ten.member.util.Sample;
import com.ten.member.vo.MemberUpdateVo;
import com.ten.member.vo.MemberVo;
import com.ten.security.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：Wqw
 * @date ：Created in 2022/12/10 0:28
 * @description：会员的功能实现层
 * @modified By：
 * @version:
 */
@Service
public class TbMemberServiceImpl implements TbMemberService {

    @Autowired
    private TbMemberDao tbMemberDao;

    /**
     * 查询会员列表,模糊查询,分页
     * page 页码
     * limit 每页显示行数
     * MemberVo 条件类 用来封装模糊查询和分页
     */
    @Override
    public Result<IPage<TbMember>> getMemberByPage(Integer page, Integer limit, MemberVo memberVo) {
        IPage<TbMember> iPage = new Page<>(page, limit);
        QueryWrapper<TbMember> wrapper = new QueryWrapper<>();
//      //模糊查询的条件
        if (StringUtils.hasText(memberVo.getMobile())) {
            wrapper.like("mobile", memberVo.getMobile());
        }
        if (StringUtils.hasText(memberVo.getNickname())) {
            wrapper.like("nickname", memberVo.getNickname());
        }
        if (StringUtils.hasText(memberVo.getStartDate())) {
            wrapper.ge("gmtCreate", memberVo.getStartDate());
        }
        if (StringUtils.hasText(memberVo.getEndDate())) {
            wrapper.le("gmtCreate", memberVo.getEndDate());
        }
        if (memberVo.getIsDisabled() != null) {
            wrapper.eq("is_disabled", memberVo.getIsDisabled());
        }

        IPage<TbMember> tbMemberIPage = tbMemberDao.selectPage(iPage, wrapper);
        return new Result<>(2000, "查询会员列表成功", tbMemberIPage);
    }


    /**
     * 修改会员信息
     * MemberUpdateVo 条件类
     */
    @Override
    public Result<TbMember> updateMemberInfo(MemberUpdateVo memberUpdateVo) {
        TbMember newMember = new TbMember();
        UpdateWrapper<TbMember> wrapper = new UpdateWrapper<>();
        if (StringUtils.hasText(memberUpdateVo.getId())) {
            wrapper.eq("id", memberUpdateVo.getId());
        }
        wrapper.eq("mobile", memberUpdateVo.getMobile());
        if (memberUpdateVo.getNickname() == null) {
            wrapper.set("nickname", "未设置昵称");
        }
        if (memberUpdateVo.getNickname() != null) {
            wrapper.set("nickname", memberUpdateVo.getNickname());
        }
        wrapper.set("sex", memberUpdateVo.getSex());
        wrapper.set("age", memberUpdateVo.getAge());
        wrapper.set("avatar", memberUpdateVo.getAvatar());
        if (StringUtils.hasText(memberUpdateVo.getRemark())) {
            wrapper.set("remark", memberUpdateVo.getRemark());
        }
        wrapper.set("gmt_modified", LocalDateTime.now());
        int update = tbMemberDao.update(newMember, wrapper);
        if (update == 1) {
            return new Result<>(2000, "修改用户信息成功");
        }
        return new Result<>(5000, "修改用户信息失败");
    }


    /**
     * 修改会员状态
     * isDisabled 讲师当前状态
     * id 讲师id
     */
    @Override
    public Result<TbMember> updateMemberStatus(Integer isDisabled, String id) {
        TbMember newMember = new TbMember();
        UpdateWrapper<TbMember> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("is_disabled", isDisabled);
        wrapper.set("gmt_modified", LocalDateTime.now());
        int update = tbMemberDao.update(newMember, wrapper);
        if (update == 1) {
            return new Result<>(2000, "修改用户状态成功");
        }
        return new Result<>(5000, "修改用户状态失败");
    }


    /**
     * 使会员type成为老师,通过审核的状态
     * 审核讲师的时候调用该方法
     * 审核通过后,根据当前用户的手机号,使用户成为讲师
     */
    @Override
    public Result<TbMember> updateTypeByMobile(String mobile) {
        UpdateWrapper<TbMember> wrapper = new UpdateWrapper<>();
        wrapper.eq("mobile", mobile);
        wrapper.set("is_deleted", 0);
        wrapper.set("is_type", 1);
        wrapper.set("gmt_modified", LocalDateTime.now());
        tbMemberDao.update(null, wrapper);
        return new Result<>(200, "该用户成为讲师");
    }


    /**
     * 通过手机号获取验证码’
     * 1，通过手机号查询该用户是否已经存在
     * 2.若该用户不存在，则发送验证码
     */
    @Override
    public Result getYanZhengMaByMobile(String mobile) {
        //1.根据手机号查询用户是否已经存在
        QueryWrapper<TbMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        TbMember tbMember = tbMemberDao.selectOne(queryWrapper);
        //如果根据手机号查到会员，说明该用户已存在
        if (tbMember != null) {
            return new Result<>(5000, "获取验证码失败！该用户已存在，请直接登录");
        } else {
            //根据手机号查不到用户，则判断其为新用户，发送验证码
            //生成4位的验证码
            String random = "" + Math.random();
            String yanZhengMa = random.substring(random.length() - 4);
            try {
                Sample.sendYzm(mobile, yanZhengMa);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(yanZhengMa);
            return new Result<>(2000, "验证码已经发送，请注意查收", yanZhengMa);
        }
    }


    /**
     * 注册功能
     **/
    @Override
    public Result<TbMember> insertNewTbMember(String mobile, String qianPassword) {
        TbMember tbMember = new TbMember();
        //雪花算法获取id
        long id = IdUtil.getSnowflakeNextId();
        tbMember.setId(id + "");
        tbMember.setMobile(mobile);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String BcPassword = passwordEncoder.encode(qianPassword);
        tbMember.setPassword(BcPassword);
        tbMember.setIsType(0);
        tbMember.setGmtCreate(LocalDateTime.now());
        tbMember.setGmtModified(LocalDateTime.now());
        int insert = tbMemberDao.insert(tbMember);
        if (insert == 1) {
            return new Result<>(2000, "用户注册成功，请登录");
        }
        return new Result<>(5000, "用户注册失败！请重新注册");
    }


    /**
     * 登录功能
     */
    @Override
    public Result<TbMember> qianLogin(String mobile, String password) {
        //1.根据手机号查询用户是否已经存在
        QueryWrapper<TbMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        TbMember tbMember = tbMemberDao.selectOne(queryWrapper);
        System.out.println("_________"+tbMember.getIsDisabled());
        if(tbMember.getIsDisabled()==1){
            return new Result(4000, "用户已禁用!");
        }
        TbMember tbMember1 = tbMemberDao.selectByMobile(mobile);
        PasswordEncoder ps = new BCryptPasswordEncoder();
        boolean matches = ps.matches(password, tbMember1.getPassword());
        if (matches) {
            HttpServletResponse response = WebUtil.getResponse();
            response.setContentType("application/json;charset=utf-8");
            ConcurrentHashMap<String,Object> map = new ConcurrentHashMap<>();
            map.put("isType",tbMember1.getIsType());
            map.put("mobile",tbMember1.getMobile());
            map.put("id",tbMember1.getId());
            //按照账户和权限生产token
            String token = JWTUtil.createJWT(map);
            map.clear();
            map.put("token",token);
            map.put("isType",tbMember1.getIsType());
            map.put("mobile",tbMember1.getMobile());
            map.put("id",tbMember1.getId());
            return new Result(2000, "登陆成功", map);
        }
        return new Result(4000, "登陆失败");
    }

    /**
     * 个人中心(刚注册的用户信息为空，需要点击修改完善)
     * 通过用户手机号查询用户信息
     * 回显到页面
     */
    @Override
    public Result<TbMember> selectByMobile(String mobile) {
        QueryWrapper<TbMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        TbMember tbMember = tbMemberDao.selectOne(wrapper);
        return new Result<>(2000, "成功查询到该用户信息", tbMember);
    }

    /**
     * 通过手机号获取验证码用来实现功能
     */
    @Override
    public Result updateYanZhengMaByMobile(String mobile) {
        //根据手机号查不到用户，则判断其为新用户，发送验证码
        //生成4位的验证码
        String random = "" + Math.random();
        String yanZhengMa = random.substring(random.length() - 4);
        try {
            Sample.sendYzm(mobile, yanZhengMa);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(yanZhengMa);
        return new Result(2000, "验证码已经发送，请注意查收", yanZhengMa);
    }

    /**
     * 修改密码
     */
    @Override
    public Result updatePasswordByMobile(String mobile, String newPassword) {
        UpdateWrapper<TbMember> wrapper = new UpdateWrapper<>();
        wrapper.eq("mobile", mobile);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(newPassword);
        wrapper.set("password", password);
        int update = tbMemberDao.update(null, wrapper);
        if (update == 1) {
            return new Result<>(2000, "修改密码成功");
        }
        return new Result(5000, "修改密码失败");
    }

    /**
     * 根据mobile手机号查询member信息，供课程微服务进行调用
     *
     * @param mobile
     * @return
     */
    @Override
    public Result<TbMember> getMemberByMobile(String mobile) {
        TbMember tbMember = tbMemberDao.selectByMobile(mobile);
        if (tbMember != null) {
            return new Result<>(200, "查询成功", tbMember);
        }
        return new Result<>(500, "查询失败");
    }
}
